package coder.config;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 创建并配置一个RedisTemplate实例
     * 该实例用于与Redis数据库进行交互，支持键值操作
     *
     * @param factory RedisConnectionFactory实例，用于连接Redis服务器
     * @return RedisTemplate<String, String> 配置好的RedisTemplate实例
     */
    @Bean(name = "redisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        // 创建RedisTemplate实例
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        // 设置连接工厂，用于建立与Redis的连接
        redisTemplate.setConnectionFactory(factory);
        // 设置键的序列化方式为StringRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置值的序列化方式为GenericJackson2JsonRedisSerializer，支持复杂对象的序列化和反序列化
//        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置哈希表键的序列化方式为StringRedisSerializer
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        // 设置哈希表值的序列化方式为GenericJackson2JsonRedisSerializer
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 初始化RedisTemplate，确保所有必需的属性都已设置
        redisTemplate.afterPropertiesSet();
        // 返回配置好的RedisTemplate实例
        return redisTemplate;
    }
}
